﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json;

namespace BasePlatformCommon
{
	[JsonObject(MemberSerialization.OptIn)]
	public class SubPort : Device
	{
		[JsonProperty]
		public int PortHardNum { get; set; }		// 端口硬件序号

		[JsonProperty]
		public int TotalLampNum { get; set; }		// 端口总灯点数

		[JsonProperty]
		public int ErrorLampNum { get; set; }		// 端口异常灯点数

		public List<Lamp> LampList { get; set; }	// 端口灯具数据集合

		// 构造函数
		public SubPort()
		{
			deviceType = DeviceType.SubPort;

			this.name = "端口";
			if (LanguageOper.available == true)
			{
				this.name = LanguageOper.ReadValue("Chain", "subPort.name");
			}

			TotalLampNum = 0;
			ErrorLampNum = 0;
			PortHardNum = 1;
			LampList = new List<Lamp>();
		}

		#region Json交互相关操作

		// 设置分控端口数据
		public void setSubPortData(JObject jsonData)
		{
			try
			{
				TotalLampNum = (int)jsonData["TotalLampNum"];
				PortHardNum = (int)jsonData["PortHardNum"];
				
				for (int lampIndex = 0; lampIndex < TotalLampNum; lampIndex++)
				{
					string lampNameStr = "Lamp" + lampIndex.ToString();
					parseSubPortData((JObject)jsonData[lampNameStr]);
				}
			}
			catch
			{
				Log.DebugLogger.Error("SubPort Parse Error!");
			}
			
			parseErrorCommLampNum();
		}

		// 解析分控端口数据
		private void parseSubPortData(JObject jsonData)
		{
			Lamp lamp = new Lamp();
			lamp.setLampData(jsonData);
			LampList.Add(lamp);
		}

		// 解析链路上的异常通讯灯具数量
		private void parseErrorCommLampNum()
		{
			ErrorLampNum = 0;
			for (int index = 0; index < TotalLampNum; index++)
			{
				if (LampList[index].CommState != 0)
				{
					ErrorLampNum++;
				}
			}
		}

		#endregion

		// 拼接提示信息
		public string buildTipMessage()
		{
			string formatStr = "检测到 {0} 个, 其中 {1} 个故障";
			if (LanguageOper.available == true)
			{
				formatStr = LanguageOper.ReadValue("Chain", "subPort.formatStr");
			}

			StringBuilder sb = new StringBuilder();
			
			sb.Append(String.Format(formatStr, TotalLampNum, ErrorLampNum));

			tipMessage = sb.ToString();
			
			return tipMessage;
		}

        public string buildTipMessage(int num) {
            string formatStr = "应有 {0} 个,";
            //if (LanguageOper.available == true) {
            //    formatStr = LanguageOper.ReadValue("Chain", "subPort.formatStr");
            //}

            StringBuilder sb = new StringBuilder();

            sb.Append(String.Format(formatStr, num));

            tipMessage = sb.ToString() + buildTipMessage();

            return tipMessage;
        }
	
	}
}
